#!/usr/local/bin/php 

<?php
//================ Get Inputs ======================//

/*
if($argc != 8){
    die("Usage: [1]type of alignment [2]input directory [3]output directory [4]suffix [5]thumbimg [6]sep [7]genes per page\n");
}
$type = trim($argv[1]);
$indir = trim($argv[2]);
$outdir = trim($argv[3]);
$suffix = trim($argv[4]);
$thumb = trim($argv[5]);
$sep = trim($argv[6]);
$nofp = trim($argv[7]);

$numlink = 50;
$type = "blastn";
$indir = "/groups/cgpdb/blastresult_display/test/";
$outdir = "/groups/cgpdb/blastresult_display/temp/";
$suffix = "vs.UCO.Arab_thal.blastn";
*/

fwrite(STDOUT, "1. Please select the type of the aligement(enter the letter and press return)\n"); 
$types = array ( 
    'a'=>'blastn', 
    'b'=>'tblastn', 
    'c'=>'blastx', 
    'd'=>'blastp',
); 
fwrite(STDOUT, "Enter 'q' to quit\n"); 

foreach ( $types as $choice => $type ) { 
    fwrite(STDOUT, "\t$choice: $type\n"); 
} 
do { 
    $selection = fgetc(STDIN); 
} while ( trim($selection) == '' ); 

if (array_key_exists($selection,$types) ) { 
    $type = $types[$selection];
    fwrite(STDOUT, "...You picked {$type}\n\n"); 
}else{
    fwrite(STDOUT, "...Unknown type {$type}\n\n"); 
    exit(0);
}

fwrite(STDOUT, "2. Please provide the directory of the input files\n"); 
do { 
    $indir = trim(fgets(STDIN));
} while ( $indir == '' ); 
fwrite(STDOUT, "...The input files are in the directory {$indir}\n\n");  

fwrite(STDOUT, "3. Please provide the directory of the output files\n"); 
do { 
    $outdir = trim(fgets(STDIN));
} while ($outdir == '' ); 
fwrite(STDOUT, "...The output files are in the directory {$outdir}\n\n");  

fwrite(STDOUT, "4. Please provide the suffix of the file names\n"); 
do { 
    $suffix = trim(fgets(STDIN));
} while ( $suffix == '' ); 
fwrite(STDOUT, "...The suffix of the file names are {$suffix}\n\n"); 
 
fwrite(STDOUT, "5. Do you want thumb images in the index page?(Y or N, defult: N)\n"); 
$thumb = trim(fgets(STDIN));
if($thumb == ''){$thumb = 'N';} 
fwrite(STDOUT, "...You choose {$thumb}\n\n");

fwrite(STDOUT, "6. Do you want seperate genes in the different pages?(Y or N, defult: N)\n"); 
$sep = trim(fgets(STDIN));
if($sep == ''){$sep = 'N';} 
fwrite(STDOUT, "...You choose {$sep}\n\n");

$nofp = 100; 
if($sep == 'Y'){
    fwrite(STDOUT, "7. The number of genes in one page?(Default:100)\n"); 
    $nofp = trim(fgets(STDIN));
    if($nofp == ''){$nofp = 100;} 
    fwrite(STDOUT, "...You choose {$nofp} images per page\n\n");  
}

$coeff = 1;
fwrite(STDOUT, "8. Please provide the coefficient:(integer, default:1)\n");
$coeff = trim(fgets(STDIN));
if($coeff == ''){$coeff = 1;}
fwrite(STDOUT, "...You choose {$coeff}\n\n");

//================ Get Blast Files ======================//

$command1 = "ls $indir | grep '.all_hits' | wc -l";
$pattern = ".".$suffix.".all_hits\n";
$command2 = "ls $indir | grep '.all_hits' | perl -p -i -e 's/".$pattern."/\t/g' " ;

$num = exec($command1) or die("Can't execute $command1\n");
$ids = exec($command2) or die("Can't execute $command2\n");
$idlist = explode("\t", $ids);

if($num != count($idlist)){
    die("Not Match!\n");
}


foreach($idlist as $geneid){		
    print($geneid."\n");
    print_blastresult($geneid,$suffix,$type,$indir,$outdir, $thumb);
}


if($thumb == 'Y' || $thumb == 'y'){
    $nofl = 4;
}else{
    $nofl = 10;
}
$title = "Blast Result of $type $suffix";

if($sep == 'Y' || $sep == 'y'){
    $pagenum = ceil($num/$nofp); 
}else{
    $pagenum =1;
    $nofp = $num;
}
for ($i=0; $i<$pagenum; $i++){
    $start=$i*$nofp+1;
    $end=($i+1)*$nofp;
    if($end>$num){$end=$num;}

    if($i != 0){
        $filename = $outdir."/index_$i.html";
    }else{
        $filename = $outdir."/index.html";
    }
    $fp = fopen($filename, "x") or die("Could not open out file to write $namefile\n"); 
    print_html($fp, $i);
    fclose($fp);
}



//================ write Index Html File==================== //
function print_html($fp, $page){
    global $title, $nofl, $nofp, $pagenum, $num, $type, $thumb, $idlist, $outdir;

    fwrite($fp, "<html>\n");
    fwrite($fp, "<head>\n");
    fwrite($fp, "<meta http-equiv=\"expires\" content=\"0\">\n");
    fwrite($fp, "<meta http-equiv=\"Pragma\" content=\"no-cache\">\n");
    fwrite($fp, "<meta http-equiv=\"Content-Control\" content=\"no-cache\">\n");
    fwrite($fp, "<title>$title</title>\n");
    fwrite($fp, "</head>\n");
    fwrite($fp, "<body>\n");
    fwrite($fp, "<h2>$title</h2><p>\n");
    fwrite($fp, "<table align=center width=100%>\n");
    fwrite($fp,  "<tr><td colspan=$nofl>View Aligments:&nbsp;&nbsp;&nbsp;");
    fwrite($fp, "<a href='index.html'>1~$nofp</a>&nbsp;&nbsp;&nbsp;");
    for ($i=1; $i<$pagenum; $i++){
        $start=$i*$nofp+1;
        $end=($i+1)*$nofp;
        if($end>$num){$end=$num;}
        fwrite($fp, "<a href='index_$i.html'>$start~$end</a>&nbsp;&nbsp;&nbsp;");
    }
    fwrite($fp, "<hr></td></tr>\n");	

    $start=$page*$nofp+1;
    $end=($page+1)*$nofp;
    if($end>$num){$end=$num;}
    fwrite($fp, "<tr><td colspan=$nofl>Alignments: $start~$end</td></tr>\n");
    for ($j=0; $j<$nofp; $j++){
        $idnum=$page*$nofp+$j;
        if($idnum<$num){
            $geneid = $idlist[$idnum];
            print($geneid."\n");

            $outfile = $geneid."_blastresult_".$type.".html";		
            if($thumb == 'Y' || $thumb == 'y'){
                $outthumb = $geneid."_blastresult_".$type."_thumb.png";
                $outthumbfile = $outdir."/".$outthumb;
                if(file_exists($outthumbfile)){
                    fwrite($fp, "<td width='25%' height='120'><a href='$outfile'>$geneid<br><img src='$outthumb'/></a></td>\n");
                }else{
                    fwrite($fp, "<td width='25%' height='120'><a href='$outfile'>$geneid<br></a></td>\n");
                }			
            }else{
                    fwrite($fp, "<td width='10%' height='50'><a href='$outfile'>$geneid<br></a></td>\n");
            }		
            if($idnum == $num){
                fwrite($fp, "</tr>\n");
            }elseif((($idnum+1) % $nofl) == 0){
                fwrite($fp, "</tr><tr><td colspan=$nofl></td></tr><tr>");
            }
        }
    }
    fwrite($fp, "</table></p></body></html>\n");
}

//================ Get Hits ======================//

function print_blastresult($geneid, $suffix, $type, $indir, $outdir, $thumb)
{
    $file = $indir."/".$geneid.".".$suffix.".all_hits";	//blast all_hits file
    $blastfile = $indir."/".$geneid.".".$suffix;		//blast out file
    $outimgname = $geneid."_blastresult_".$type.".png";	
    $outimg = $outdir."/".$outimgname;	//blast out image
    $outimgthumb = $outdir."/".$geneid."_blastresult_".$type."_thumb.png";	
    $outfile = $outdir."/".$geneid."_blastresult_".$type.".html";		//blast out html

    //print("$file\n$blastfile\n$outimg\n$outfile\n");

    if($type == 'blastn'){
        $scale = 3;
        $bscale = 3;
    }elseif($type == 'tblastn'){
        $scale = 1;
        $bscale = 3;
    }elseif($type == 'blastx'){
        $scale = 3;
        $bscale = 1;
    }elseif($type == 'blastp'){
        $scale = 1;
        $bscale = 1;
    }else{
        die("Invalid blast type!\n");
    }


    $S = array();
    $Hits = 0;
    $genelen = 0;
    $fp = fopen($file, "r") or die ("Could not open file $file");

    while ($info = fscanf($fp, "%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\n"))
    {
        list($barb, $bare, $lbar, $rbar) = array(0, 0, 0, 0);
        list($lout, $rout) = array('no', 'no');
        if($type == 'blastp'){
            list($q, $id, $exp, $per, $num, $mlen, $pri, $alt, $align, $qb, $qe, $sb, $se, $delimit, $qlen, $slen, $gap) = $info;
        }else{
            list($q, $id, $exp, $per, $num, $mlen, $pri, $alt, $align, $frame, $qb, $qe, $sb, $se, $delimit, $qlen, $slen, $gap) = $info;
        }
        if($id != "no_hits_found"){
            if($type == 'blastp'){
                if($sb!=0){$lbar=$sb;}
                if($se!=$slen){$rbar=$slen-$se;}
                list($barb, $bare) = array( (int)($qb/$scale), (int)($qe/$scale));
            }else{
                if($type == 'blastn'){
                    if($frame == "+/+"){
                        if($sb!=0){$lbar=$sb;}
                        if($se!=$slen){$rbar=$slen-$se;}
                        list($barb, $bare) = array( (int)($qb/$scale), (int)($qe/$scale));
                    }elseif($frame == "+/-"){
                        if($se!=0){	$rbar=$se;}
                        if($sb!=$slen){$lbar=$slen-$sb;}
                        list($barb, $bare) = array( (int)($qb/$scale), (int)($qe/$scale));
                    }elseif($frame == "-/+" || $frame == "-/-"){
                        die("Error: Unknown frame $frame");	 
                    }
                }else{
                    $shift = substr($frame, 0, 1);
                    if($shift == "+"){
                        if($sb!=0){$lbar=$sb;}
                        if($se!=$slen){$rbar=$slen-$se;}
                        list($barb, $bare) = array( (int)($qb/$scale), (int)($qe/$scale));
                    }elseif($shift == "-"){
                        if($se!=0){	$rbar=$se;}
                        if($sb!=$slen){$lbar=$slen-$sb;}
                        list($barb, $bare) = array( (int)($qb/$scale), (int)($qe/$scale));
                    }
                }
            }

            $genelen=$qlen;
            $genebarlen=(int)($genelen/$scale);
            list($lbar, $rbar) = array( (int)($lbar/$bscale), (int)($rbar/$bscale));

            if($lbar-(int)($qb/$scale)>50){$lout='yes';}
            if($rbar-$genebarlen+(int)($qe/$scale)>50){$rout='yes';}

            if(!isset($S[$id])){
                $S[$id] = array();
            }   

            array_push($S[$id], array($qb, $qe, $sb, $se, $per, $barb, $bare, $lbar, $rbar, $lout, $rout));
            //print_r($S[$id]);
            $Hits++;
        }
    }
    fclose($fp);


    //------------- generate html file ------------------------//
    
    $webp = fopen($outfile, "x") or die("Could not open out file to write $outfile\n");
    $title = $geneid." Blast Search";
     
    fwrite($webp, "<html>\n");
    fwrite($webp, "<head>\n");
    fwrite($webp, "<meta http-equiv=\"expires\" content=\"0\">\n");
    fwrite($webp, "<meta http-equiv=\"Pragma\" content=\"no-cache\">\n");
    fwrite($webp, "<meta http-equiv=\"Content-Control\" content=\"no-cache\">\n");
    fwrite($webp, "<title>$title</title>\n");
    fwrite($webp, "</head>\n");
    fwrite($webp, "<body><center>\n");
    fwrite($webp, "<h2>$title</h2>\n");
    if($Hits !=0){
        $map = drawimg($geneid, $genelen, $genebarlen, $Hits, $S, $outimg, $outimgthumb, $thumb);
        fwrite($webp, "<img src='".$outimgname."' border='2' usemap='#idmap'>\n");
        fwrite($webp, "<map id='idmap' name='idmap'>");
        foreach ($map as $coords => $sbid){
            fwrite($webp, "<area shape='rect' coords='".$coords."' alt=$sbid href='#link_$sbid'>\n");
        }
        fwrite($webp, "</map>");
    }
    fwrite($webp, "</center>");

    fwrite($webp, "<pre>");
    $gp = fopen($blastfile, "r") or die ("Could not open blast file $blastfile\n");
    $line = fgets($gp, 4096);
    while(!feof($gp))
    {
        if ((substr($line, 0, 4) == ">gi|") || (substr($line, 0, 3) == "gi|"))
        {
            $temp = split("\|", $line, 3);
            if(substr($line, 0, 4) == ">gi|"){
                fwrite($webp, $temp[0]."|<a name='link_".$temp[1]."' href='javascript:void(0);'>$temp[1]</a>".$temp[2]);
            }else{
                fwrite($webp, $line);
            }
        }elseif(substr($line, 0, 1) == ">"){
            $line = trim($line);
            $line = ltrim($line, '>');
            $temp = split(" ", $line, 2);
            fwrite($webp, "><a name='link_".$temp[0]."' href='javascript:void(0);'>$temp[0]</a>");
            if(isset($temp[1])){
                fwrite($webp, " $temp[1]\n");
            }else{
                fwrite($webp, "\n");
            }	
        }else{
            fwrite($webp, $line);
        }
        $line = fgets($gp, 4096);
    }
    fclose($gp);

    fwrite($webp, "</pre>");
    fwrite($webp, "</body></html>\n");

    fclose($webp);
}


function colormap($per, $Color){
	
    if($per < 80){
	$n = 6;
    }else{
	$n = (int)((105 - $per) / 5);
    }
    return $Color[$n];
}


//================ Draw Alignment Results ======================//

function drawimg($geneid, $genelen, $genebarlen, $Hits, $S, $outimg, $outimgthumb, $thumb){

    global $chartW, $chartH;

    //================ Setup graph ======================//
    //--- Size
  
    list($gutterW, $gutterH, $idW, $outW, $barH, $gap, $extra)= array(25, 5, 150, 50, 10, 8, 2);
    list($tinyfont, $smallfont, $mediumfont) = array(1, 2, 3);
    $chartW = $genebarlen+($gutterW*2)+$idW+($outW*2);
    $chartH = $Hits*($barH+($gap*3)+($extra*2))+ 75;
    $image = imagecreate($chartW, $chartH) or die("Cannot Initialize new GD image stream");
  
    //--- Colors
    $white = imagecolorallocate($image, 255, 255, 255);
    $black = imagecolorallocate($image, 0, 0, 0);
    $blue = imagecolorallocate($image, 96, 0, 255);
    $red = imagecolorallocate($image, 255, 0, 0);
    $gray = imagecolorallocate($image, 204, 204, 204);
    $light = imagecolorallocate($image, 228, 228, 228);
    $dark = imagecolorallocate($image, 128, 128, 128);
    $magenta = imagecolorallocate($image, 255, 150, 255);
    $green = imagecolorallocate($image, 150, 255, 150);
    $yellow = imagecolorallocate($image, 255, 255, 150);
    $orange = imagecolorallocate($image, 255, 153, 0);
    $purple = imagecolorallocate($image, 128, 0, 128);
    $Color = array($black, $purple, $blue, $magenta, $orange, $yellow, $green, $red, $gray, $light, $dark, $white);
  
    //--- Percent identity key
  
  
    imagefilledrectangle($image, 0, 0, $chartW, $chartH, $white);
    imagestring($image, $smallfont, $chartW-100, $gutterH, "% Identity", $black);
    $x=$chartW-100;
    for ($i = 75; $i <= 100; $i += 5) {
        $x = $x-20;
        imagefilledrectangle($image, $x, $gutterH, $x+10, $gutterH+$barH, colormap($i, $Color));
        if($i<80){
            imagestring($image, $tinyfont, $x, $gutterH+$barH+$extra, '<80', $black);
        }else{
            imagestring($image, $tinyfont, $x, $gutterH+$barH+$extra, $i, $black);
        }
    }
  
    //--- draw gene
    $curH=$gutterH+$barH+$extra+$gap;
    $curW=$gutterW+$idW+$outW;
    imagestring($image, $smallfont, $gutterW, $curH, $geneid, $black);
    imagestring($image, $tinyfont, $curW, $curH, 1, $black);
    imagestring($image, $tinyfont, $curW+$genebarlen, $curH, $genelen, $black);
    $curH = $curH+$gap;
    imagefilledrectangle($image, $curW, $curH, $curW+$genebarlen, $curH+$barH, $red);
    imagestring($image, $tinyfont, $curW+1, $curH, $geneid, $white);
  
    $curH = $curH+$barH+$gap;
  
    //--- draw alignments
    $v=0;
    list($x1, $x2, $y1, $y2) = array(0, 0, 0, 0);
    $pos="";
    $map = array();
    foreach ($S as $id => $same) {
        $curH=$curH+$gap;
        imagestring($image, $smallfont, $gutterW, $curH+$gap, $id, $black);
        $x1=$gutterW;
        $y1=$curH+$gap;
        $x2=$gutterW+50;
        $y2=$curH+($gap*2);
        $pos = "$x1, $y1, $x2, $y2";
        $map[$pos]=$id;
    
        $gnum=count($same);
        $dist=$gnum*(($gap*3)+$barH+($extra*2));
        if($v%2==0){
            $fill=$gray;
        }else{
            $fill=$light;
        }
        imagefilledrectangle($image, $curW-$outW, $curH, $chartW-$gutterW, $curH+$dist, $fill);
        foreach ($same as $n => $val) {
            list($qb, $qe, $sb, $se, $per, $barb, $bare, $lbar, $rbar, $lout, $rout) = $val;
            $curH=$curH+$extra;
            imagestring($image, $tinyfont, $barb+$curW, $curH, $qb, $black);
            imagestring($image, $tinyfont, $bare+$curW, $curH, $qe, $black);
            $curH=$curH+$gap;
            $fill=colormap($per, $Color);
            imagefilledrectangle($image, $barb+$curW, $curH, $bare+$curW, $curH+$barH, $fill);
            $x1=$barb+$curW;
            $y1=$curH;
            $x2=$bare+$curW;
            $y2=$curH+$barH;
            if($lbar != 0){
                if($lout != 'yes'){
                    imagefilledrectangle($image, $barb+$curW-$lbar, $curH, $barb+$curW, $curH+$barH, $dark);
                    $x1=$barb+$curW-$lbar;
                }else{
                    imagefilledrectangle($image, $curW-$outW, $curH, $barb+$curW, $curH+$barH, $dark);
                    imagefilledrectangle($image, $curW-40, $curH, $curW-39, $curH+$barH, $white);
                    imagefilledrectangle($image, $curW-30, $curH, $curW-29, $curH+$barH, $white);				
                    imagefilledrectangle($image, $curW-20, $curH, $curW-19, $curH+$barH, $white);				
                    $x1=$curW-$outW;
                }	
            }
            if($rbar != 0){
                if($rout != 'yes'){
                    imagefilledrectangle($image, $bare+$curW, $curH, $bare+$curW+$rbar, $curH+$barH, $dark);
                    $x2=$bare+$curW+$rbar;
                }else{
                    imagefilledrectangle($image, $bare+$curW, $curH, $curW+$genebarlen+$outW, $curH+$barH, $dark);
                    imagefilledrectangle($image, $curW+$genebarlen+19, $curH, $curW+$genebarlen+20, $curH+$barH, $white);
                    imagefilledrectangle($image, $curW+$genebarlen+29, $curH, $curW+$genebarlen+30, $curH+$barH, $white);
                    imagefilledrectangle($image, $curW+$genebarlen+39, $curH, $curW+$genebarlen+40, $curH+$barH, $white);
                    $x2=$curW+$genebarlen+$outW;
                }		
            }
            imagestring($image, $tinyfont, $barb+$curW+1, $curH, $id, $white);		
            $curH=$curH+$barH+$extra;
            imagestring($image, $tinyfont, $barb+$curW, $curH, $sb, $black);
            imagestring($image, $tinyfont, $bare+$curW, $curH, $se, $black);
            $curH=$curH+$gap;
            $pos = "$x1, $y1, $x2, $y2";
            $map[$pos]=$id;
        }
        $v++;
    }
    //--- Output image
    imagepng($image, $outimg) or die("Could not output image file $outimg\n");
    if($thumb == 'Y' || $thumb == 'y'){
        $imgthumb = imagecreatetruecolor(200, 100) or die("Cannot Initialize new GD image stream");
        $width = imagesx($image);
        $height = (int)($width/2);
        imagecopyresampled($imgthumb, $image, 0, 0, 0, 0, 200, 100, $width, $height);
        imagepng($imgthumb, $outimgthumb) or die("Could not output image file $outimg\n");
    }
  
    return $map;

}
	

?>